
//
// Says to the compiler which is our clock frequency, permits the delay 
// functions to be very accurate
//
#define F_CPU 16000000UL

//
// The baud rate from boards.txt.
// The baudrate that we want to use
//
#define BAUD 115200
//
// he formula that does all the required maths
//
#define BAUD_PRESCALLER (((F_CPU / (BAUDRATE * 16UL))) - 1)

// ==========================================================================
//   USART_init
// ==========================================================================
void USART_init (void)
{
 UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8);
 UBRR0L = (uint8_t)(BAUD_PRESCALLER);
 UCSR0B = (1<<RXEN0)|(1<<TXEN0);
 UCSR0C = ((1<<UCSZ00)|(1<<UCSZ01));
}

// ==========================================================================
//   USART_send
//
//   Send one char from the Arduino.
// ==========================================================================
void USART_send (unsigned char data)
{
  //
  // The first line is a bit odd, but it as its reasons, that line is 
  // checking if there is space in the Atmega send buffer(the atmega 
  // chip as a small 3 byte hardware buffer in the TX/send channel) to 
  // put a new char/byte, if yes the char/byte is loaded into the UDR0 
  // register which makes part of the USART hardware and if something 
  // is loaded into that register it will be sent by the USART.
  //
  while(!(UCSR0A & (1<<UDRE0)));
  UDR0 = data;
}

// ==========================================================================
//   USART_receive
//
//   Receive one char.
// ==========================================================================
unsigned char USART_receive (void)
{ 
  //
  // pool the receive register, and if there is new data in that register 
  // we return the data
  //
  while(!(UCSR0A & (1<<RXC0)));
  return UDR0;
 
}

// ==========================================================================
//   USART_putstring
// ==========================================================================
void USART_putstring (char* StringPtr)
{
  while (*StringPtr != 0x00){    
    //
    // Here we check if there is still more chars to send, this is done 
    // checking the actual char and see if it is different from the null 
    // char
    //
    USART_send(*StringPtr);
    StringPtr++;
  }
 
}
